package com.java.api;

import java.io.*;

class Message implements Serializable {
    private static final long serialVersionUID = -8435126653107452568L;
    private Integer id;
    private String content;
    public void setContent(String content) {
        this.content = content;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public Integer getId() {
        return id;
    }
    public String getContent() {
        return content;
    }

    @Override
    public String toString() {
        return "Message{" +
                "id=" + id +
                ", content='" + content + '\'' +
                '}';
    }
}

public class SerializableTests {
    static byte[] serialize() throws IOException {
        //1.对象序列化
        //字节数组输出流(内置一个字节数组)
        ByteArrayOutputStream byteArray=new ByteArrayOutputStream();
        //对象输出流对象,基于此对象可以完成对象的序列化
        ObjectOutputStream out=new ObjectOutputStream(byteArray);//
        //对象序列化
        Message msg=new Message();
        msg.setId(100);
        msg.setContent("hello jsd2302");
        out.writeObject(msg);
        out.close();
        return byteArray.toByteArray();
    }
    static Object deserialize(byte[] array) throws IOException, ClassNotFoundException {
        //2.对象的反序列化
        //构建字节数组输入流
        ByteArrayInputStream inArray=new ByteArrayInputStream(array);
        //构建对象输入流
        ObjectInputStream in=new ObjectInputStream(inArray);
        //反序列化
        return in.readObject();
    }
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        byte[] array=serialize();
        //==================
        Object obj=deserialize(array);
        System.out.println(obj);
    }
}
